//
//  CertificationPhotoCell.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/5.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import TZImagePickerController
import MobileCoreServices

class CertificationPhotoCell: UITableViewCell,TZImagePickerControllerDelegate {
    
    var positiveImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = colorWith255RGB(173, g: 216, b: 247)
        
        let aImageView = UIImageView()
        aImageView.image = UIImage(named: "background_上传")
        aImageView.contentMode = .scaleAspectFit
        imageView.addSubview(aImageView)
        aImageView.snp.makeConstraints({ (make) in
            make.centerX.equalTo(imageView)
            make.centerY.equalTo(imageView.snp.centerY).offset(-10)
            make.width.height.equalTo(40)
        })
        
        let label = UILabel()
        label.text = "上传"
        label.textColor = UIColor.white
        label.font = wwFont_Regular(16)
        imageView.addSubview(label)
        label.snp.makeConstraints({ (make) in
            make.centerX.equalTo(aImageView)
            make.top.equalTo(aImageView.snp.bottom).offset(3)
        })
        
        
        return imageView
    }()
    
    var positiveLabel: UILabel = {
        let label = UILabel()
        label.text = "身份证正面照"
        label.font = wwFont_Regular(15)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    var reverseImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = colorWith255RGB(173, g: 216, b: 247)
        
        let aImageView = UIImageView()
        aImageView.image = UIImage(named: "background_上传")
        aImageView.contentMode = .scaleAspectFit
        imageView.addSubview(aImageView)
        aImageView.snp.makeConstraints({ (make) in
            make.centerX.equalTo(imageView)
            make.centerY.equalTo(imageView.snp.centerY).offset(-10)
            make.width.height.equalTo(40)
        })
        
        let label = UILabel()
        label.text = "上传"
        label.textColor = UIColor.white
        label.font = wwFont_Regular(16)
        imageView.addSubview(label)
        label.snp.makeConstraints({ (make) in
            make.centerX.equalTo(aImageView)
            make.top.equalTo(aImageView.snp.bottom).offset(3)
        })
        
        return imageView
    }()
    
    var reverseLabel: UILabel = {
        let label = UILabel()
        label.text = "身份证反面照"
        label.textColor = UIColor.mg_lightGray
        label.font = wwFont_Regular(15)
        return label
    }()

    var positivePhoto: UIImage?{
        willSet {
            if newValue != nil {
                self.positiveImageView.image = newValue
                
                for view in self.positiveImageView.subviews {//将imageView上的子视图都剔除
                    view.removeFromSuperview()
                }
                
                if let handler = self.positivePhotoSelectedHandler {
                    handler(newValue!)
                }
            }
        }
    }
    var reversePhoto: UIImage? {
        willSet {
            if newValue != nil {
                self.reverseImageView.image = newValue
                
                for view in self.reverseImageView.subviews {//将imageView上的子视图都剔除
                    view.removeFromSuperview()
                }
                
                if let handler = self.reversePhotoSelectedHandler {
                    handler(newValue!)
                }
            }
        }
    }
    
    var positivePhotoSelectedHandler: ((UIImage) -> Void)?
    var reversePhotoSelectedHandler: ((UIImage) -> Void)?
    
    var isPositivePhoteSelected: Bool!
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        
        self.positiveImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doPositiveAction)))
        self.reverseImageView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doReverseAction)))
        
        self.setupViews()
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews() {
        self.contentView.addSubview(self.positiveImageView)
        self.positiveImageView.snp.makeConstraints { (make) in
            make.top.equalTo(self.contentView).offset(10)
            make.right.equalTo(self.contentView.snp.centerX).offset(-10)
            make.width.equalTo(150)
            make.height.equalTo(80)
        }
        
        self.contentView.addSubview(self.positiveLabel)
        self.positiveLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.positiveImageView.snp.bottom)
            make.centerX.equalTo(self.positiveImageView)
//            make.height.equalTo(10)
            make.bottom.equalTo(self.contentView)
        }
        
        self.contentView.addSubview(self.reverseImageView)
        self.reverseImageView.snp.makeConstraints { (make) in
            make.top.equalTo(self.contentView).offset(10)
            make.left.equalTo(self.contentView.snp.centerX).offset(10)
            make.width.equalTo(150)
            make.height.equalTo(80)
        }
        
        self.contentView.addSubview(self.reverseLabel)
        self.reverseLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.reverseImageView.snp.bottom)
            make.centerX.equalTo(self.reverseImageView)
//            make.height.equalTo(10)
            make.bottom.equalTo(self.contentView)
        }
    }
    
    func doPositiveAction() {
        self.isPositivePhoteSelected = true
        
        
        self.doAvatarView()
    }
    
    func doReverseAction() {
        self.isPositivePhoteSelected = false
        
        self.doAvatarView()
    }
    
    
    func doAvatarView() {
        var vc: CertificationSubmitController!
        var responder = self.next
        while !(responder is UIViewController) {
            responder = responder?.next
        }
        if responder is CertificationSubmitController {
            vc = responder as! CertificationSubmitController
        }
        
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let takePhotoAction = UIAlertAction(title: "拍照", style: .default) { (action) in
//            let imagePickerController = UIImagePickerController()
//            imagePickerController.delegate = self
//            imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
//            imagePickerController.allowsEditing = true
//            imagePickerController.showsCameraControls = true
//            imagePickerController.cameraDevice = UIImagePickerControllerCameraDevice.rear
//            imagePickerController.mediaTypes = [kUTTypeImage as String]
//            
//            vc.present(imagePickerController, animated: true, completion: nil)
            let homeC = PureCamera()
            homeC.fininshcapture = {[unowned self](image) in
                if image != nil {
                    let aImage = UIImage(cgImage: image!.cgImage!, scale: image!.scale, orientation: UIImageOrientation.left)
                    
                    if self.isPositivePhoteSelected {
                        self.positivePhoto = aImage
                    }
                    else
                    {
                        self.reversePhoto = aImage
                    }
                }
            }
            vc.present(homeC, animated: true, completion: nil)
        }
        
        let choicePhotoAction = UIAlertAction(title: "从相册选择", style: .default) { (action) in
//            let imagePicker = TZImagePickerController.init(maxImagesCount: 1, delegate: self)
//            imagePicker?.didFinishPickingPhotosHandle = {[unowned self](photos, assets,isSelectOriginalPhoto) in
//                if photos != nil {
////                    self.visiblePhoto = photos![0]
//                    if self.isPositivePhoteSelected {
//                        self.positivePhoto = photos![0]
//                    }
//                    else
//                    {
//                        self.reversePhoto = photos![0]
//                    }
//                }
//                
//            }
//            vc.present(imagePicker!, animated: true, completion: nil)
            
            let imagePickerVc = TZImagePickerController(maxImagesCount: 1, columnNumber: 3, delegate: self, pushPhotoPickerVc: true)
            imagePickerVc?.allowPickingOriginalPhoto = false//是否显示原图按钮,默认为true
            imagePickerVc?.allowPickingVideo = false//是否能选视频，默认true
            imagePickerVc?.allowTakePicture = false // 在内部显示拍照按钮
            
            imagePickerVc?.allowCrop = true//允许裁剪
            let left:CGFloat = 30;
            let width = SCREEN_WIDTH - 2 * left;
            let height = width*1.6
            let top = (SCREEN_HEIGHT-height)/2
            imagePickerVc?.cropRect = CGRect(x: left, y: top, width: width, height: height)
            imagePickerVc?.cropViewSettingBlock = {(view) in
                let descriptionLabel = UILabel()
                descriptionLabel.font = UIFont.systemFont(ofSize: 20)
                descriptionLabel.textColor = UIColor.white
                descriptionLabel.frame = CGRect(x: SCREEN_WIDTH-160, y: 0, width: 150, height: 40)
                descriptionLabel.center = CGPoint(x: descriptionLabel.center.x, y: SCREEN_HEIGHT/2-30)
                descriptionLabel.transform = CGAffineTransform.init(rotationAngle: CGFloat(Double.pi/2))
                descriptionLabel.text = "身 份 证 照 片"
                view?.addSubview(descriptionLabel)
            }
            imagePickerVc?.didFinishPickingPhotosHandle = {[unowned self](photos, _,_) in
                if photos != nil, photos!.count > 0 {
                    let photo = photos![0]
                    let aImage = UIImage(cgImage: photo.cgImage!, scale: photo.scale, orientation: UIImageOrientation.left)
                    if self.isPositivePhoteSelected {
                        self.positivePhoto = aImage
                    }
                    else
                    {
                        self.reversePhoto = aImage
                    }
                }
            }
            
            vc.present(imagePickerVc!, animated: true, completion: nil)
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertController.addAction(takePhotoAction)
        alertController.addAction(choicePhotoAction)
        alertController.addAction(cancelAction)
        vc.present(alertController, animated: true, completion: nil)
        
    }
}

extension CertificationPhotoCell: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let photo = info[UIImagePickerControllerOriginalImage]
        if photo != nil {
            if self.isPositivePhoteSelected {
                self.positivePhoto = photo as? UIImage
            }
            else
            {
                self.reversePhoto = photo as? UIImage
            }
        }
    }
}
